<template>
	<base-popup
		v-model:show="show"
		show-cancel-button
		class-name="validate-realname-dialog"
		:title="$t('validate.realname')"
		:cancel-button-text="$t('action.cancel')"
		:confirm-button-text="$t('action.confirm')"
		:confirm-button-color="confirmButtonColor"
		:before-close="beforeClose"
		@close="cancel">
		<div class="py-[13px] px-5">
			<base-title class="mb-3" :subtitle="$t('validate.contentSubtitle1')" showSubIcon />
			<base-input
				v-model.trim="realname"
				:error="realnameError"
				:label="$t('validate.contentTitle')"
				clearable />
			<p class="text-sm -mb-4 text-t-2">{{ $t('validate.cannotChange') }}</p>
		</div>

		<base-button
			class="!w-fit h-10 mx-auto mt-10 mb-10"
			type="primary"
			@click="confirm"
			:disabled="!realname">
			{{ $t('action.confirm') }}
		</base-button>
	</base-popup>
</template>

<script lang="ts" setup>
import { watch, ref, computed } from 'vue'
import { setRealname } from '@/api/profile'
import { useProfileStore } from '@/store'
import { BasePopup, BaseInput, BaseTitle, BaseButton } from '@/components/base'
import { t } from '@/utils'

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	}
})

const emits = defineEmits(['update:modelValue', 'submit'])
const profileStore = useProfileStore()

const show = ref(false)
const realname = ref('')
const realnameError = computed(() =>
	realname.value && realname.value.length < 1 ? t('realname.nameError') : ''
)

const cancel = () => {
	emits('update:modelValue', false)
	realname.value = ''
}
const confirm = async () => {
	if (realname.value) {
		emits('update:modelValue', false)
		emits('submit', realname.value)
		await setRealname({
			realname: realname.value
		})
		await profileStore.getUserInfo()
	}
}

const beforeClose = () => {
	return !!realname.value
}

const confirmButtonColor = computed(() => {
	return realname.value ? 'var(--color-primary)' : 'var(--color-disable)'
})

watch(
	() => props.modelValue,
	() => {
		show.value = props.modelValue
	}
)
</script>
<style scoped lang="scss"></style>
